import json
import os
import time
import requests
from django.conf import settings
from django.db import transaction
from django.http import HttpResponseRedirect, JsonResponse
from rest_framework import status
from rest_framework.generics import get_object_or_404
# from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from tools.bdapi import bdapi
from tools.isLoginDeco import IsLoginDeco
from tools.myjwt import mjwt
from user.models import ThirdPartyLoginModel, UserModel
from tools.thiry_party_login import ProductFactory
from user.userserializer import UserModelSerializer
from cwapi.settings import STATIC_URL
from mycelery import schedule_tasks
from tools.myredis import mredis
from rest_framework.parsers import MultiPartParser, FormParser

# Create your views here.

# 跳转钉钉接口
class LoginUrlView(APIView):
    def get(self, request):
        factory = ProductFactory()
        loginCls = factory.create_product("dingding")
        url = loginCls.get_url()
        return Response({"code": 200, 'url': url})

class CallBackView(APIView):
    def get(self, request):
        factory = ProductFactory()
        loginCls = factory.create_product("dingding")
        url = loginCls.callback(request)
        return HttpResponseRedirect(url)


class UserInfoView(APIView):
    def get(self, request):
        users = UserModel.objects.all()
        serializer = UserModelSerializer(users, many=True)
        return Response({'data': serializer.data, 'code': 200})

    def post(self, request):
        serializer = UserModelSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'data': serializer.data, 'code': 201}, status=status.HTTP_201_CREATED)
        else:
            return Response({'errors': serializer.errors, 'code': 400}, status=status.HTTP_400_BAD_REQUEST)


class UserUpdateView(APIView):
    def post(self, request, id):
        user = get_object_or_404(UserModel, id=id)

        # 获取更新的数据
        new_pic = request.FILES.get('pic_url')
        new_mobile = request.data.get('mobile')
        new_nikename = request.data.get('nikename')

        # 处理图片上传
        if new_pic:
            if user.pic_url and os.path.exists(os.path.join(settings.MEDIA_ROOT, user.pic_url.name)):
                user.pic_url.delete(save=False)

            # 保存新头像
            user.pic_url = new_pic  # Django 的 FileField 会自动保存文件

        # 更新其他字段
        if new_mobile:
            user.mobile = new_mobile
        if new_nikename:
            user.nikename = new_nikename

        # 保存更改并返回响应
        try:
            user.save()
            serializer = UserModelSerializer(user)
            pic_url = request.build_absolute_uri(user.pic_url.url) if user.pic_url else ''
            return Response({
                'data': serializer.data,
                'code': 200,
                'pic_url': pic_url  # 返回完整路径给前端
            }, status=status.HTTP_200_OK)
        except Exception as e:
            print(f'更新失败: {e}')
            return Response({'message': '更新失败', 'code': 500}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 将读取到文件写入本地
def write_file(file):
    filepath = os.path.join(STATIC_URL, file.name)
    with open(filepath, 'wb') as f:
        f.write(file.read())


# 验证实名信息
class IdCardView(APIView):
    def post(self, request):
        file = request.data.get('file')
        # print(file, type(file))
        # print(file.name)
        write_file(file)
        # 身份证验证
        file_path = os.path.join(STATIC_URL, file.name)
        # print(file_path)
        # 写入redis队列
        mredis.list_add('idcard_list', file_path)
        # print('-' * 30)
        # print(mredis.list_pop('idcard_list').decode())
        # print(mredis.list_llen('idcard_list'))
        # print(bool(mredis.list_llen('idcard_list')))
        return Response({'code': 200})
        # res = bdapi.idcard(file_path)
        # return Response({'msg': res, 'code': 200})


# 到redis中查询身份信息
class IdCardResView(APIView):
    def post(self, request):
        file = request.data.get('file')
        # print(file)
        # 从redis中读取
        file_path = os.path.join(STATIC_URL, file.name)
        res = mredis.str_get(file_path)
        if res:
            # print(res.decode())
            res = json.loads(res.decode())
        return Response({'res': res, 'code': 200})


# celery异步任务测试
class CeleryTestView(APIView):
    def get(self, request):
        # 执行异步任务
        res1 = schedule_tasks.c_test1.delay()
        # 延时执行异步任务,countdown单位秒
        res2 = schedule_tasks.c_test2.apply_async(kwargs={"name": "n1", "age": 11}, countdown=15)
        print('res1--------------', res1)
        print('res2--------------', res2)
        return Response({'message': '000'})


# 测试用户是否登录
class MyTestView(APIView):
    @IsLoginDeco
    def get(self, request):

        return Response({'message': 'user login success', 'code': 200})

















